package com.newworld.dmsapp2.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class UploadService {
	public static final int UPLOAD_SUCCESS = 0x123;
	public static final int UPLOAD_FAIL = 0x124;
	public UploadService() {
		// TODO Auto-generated constructor stub

	}

	
	/**
	 * @param url
	 *            servlet的地址
	 * @param params
	 *            要传递的参数
	 * @param files
	 *            要上传的文件
	 * @return true if upload success else false
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String uploadFileswithNon(String url, Map<String, String> params,
			ArrayList<File> files) throws ClientProtocolException, IOException {
		String sessionId = params.get("sessionId");
		HttpClient client = new DefaultHttpClient();// 开启一个客户端 HTTP 请求
		HttpPost post = new HttpPost(url);// 创建 HTTP POST 请求
		if (null != sessionId) {
			post.setHeader("Cookie", "JSESSIONID=" + sessionId);
		}

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式
		for (File file : files) {
			FileBody fileBody = new FileBody(file);// 把文件转换成流对象FileBody
			builder.addPart("files", fileBody);
		}
		
		HttpEntity entity = builder.build();// 生成 HTTP POST 实体
		post.setEntity(entity);// 设置请求参数

		HttpResponse response = client.execute(post);// 发起请求 并返回请求的响应
		if (response.getStatusLine().getStatusCode() == 200) {
			String result = EntityUtils.toString(response.getEntity());
			return result;

		}
		return null;
	}
	/**
	 * @param url
	 *            servlet的地址
	 * @param params
	 *            要传递的参数
	 * @param files
	 *            要上传的文件
	 * @return true if upload success else false
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String uploadFiles(String url, Map<String, String> params,
			ArrayList<File> files) throws ClientProtocolException, IOException {
		String sessionId = params.get("sessionId");
		HttpClient client = new DefaultHttpClient();// 开启一个客户端 HTTP 请求
		HttpPost post = new HttpPost(url);// 创建 HTTP POST 请求
		if (null != sessionId) {
			post.setHeader("Cookie", "JSESSIONID=" + sessionId);
		}

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式
		for (File file : files) {
			FileBody fileBody = new FileBody(file);// 把文件转换成流对象FileBody
			builder.addPart("files", fileBody);
		}
		if (null != params.get("houseId")) {
			builder.addTextBody("houseId", params.get("houseId"));// 设置请求参数
		}else if (null != params.get("projectId")) {
			builder.addTextBody("projectId", params.get("projectId"));// 设置请求参数
		} else if (null != params.get("repairId")) {
			builder.addTextBody("repairId", params.get("repairId"));// 设置请求参数
		}
		if (null != params.get("areaType_typecode")) {
				builder.addTextBody("areaType_typecode", params.get("areaType_typecode"));// 设置请求参数
		}
		builder.addTextBody("functionCode", params.get("functionCode"));// 设置请求参数

		HttpEntity entity = builder.build();// 生成 HTTP POST 实体
		post.setEntity(entity);// 设置请求参数

		HttpResponse response = client.execute(post);// 发起请求 并返回请求的响应
		if (response.getStatusLine().getStatusCode() == 200) {
			String result = EntityUtils.toString(response.getEntity());
			return result;

		}
		return null;
	}
	/**
	 * @param url
	 *            servlet的地址
	 * @param params
	 *            要传递的参数
	 * @param files
	 *            要上传的文件
	 * @return true if upload success else false
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static boolean downFilewithNon(String urlo, String filepath,
			Map<String, String> rawparams) throws ClientProtocolException,
			IOException {
		boolean downloadOk = false;
		String url;
		String sessionId = rawparams.get("sessionId");
		String fileName = rawparams.get("fileName");
		String path1 = filepath + fileName;
		HttpClient client = new DefaultHttpClient();// 开启一个客户端 HTTP 请求
		// url =
		// "http://10.139.19.180:8080/dpms/repairBusController.do?downloadFile&fileName=HubeiWuhanGuanggu_01_01_1_101_20151026073534_hza123456_problemvoice.mp3&functionCode=downloadRepairFile";
		url = urlo;
		HttpPost post = new HttpPost(url);// 创建 HTTP POST 请求
		if (null != sessionId) {
			post.setHeader("Cookie", "JSESSIONID=" + sessionId);
		}

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式
		// 请求超时 add by risa
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
		// 读取超时 add by risa
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
		HttpEntity entity = builder.build();// 生成 HTTP POST 实体
		post.setEntity(entity);// 设置请求参数
		File dbFile = new File(path1);
		if (!dbFile.exists()) {
			HttpResponse response = client.execute(post);// 发起请求 并返回请求的响应
			if (response.getStatusLine().getStatusCode() == 200) {

				HttpEntity respEnt = response.getEntity();

				Boolean isStream = respEnt.isStreaming();
				if (isStream) {
					try {
						InputStream fileInStream = respEnt.getContent();
						Log.e("下载文件流大小", "下载文件大小=" + respEnt.getContentLength());

						File file = new File(path1);
						FileOutputStream fileOutStream = new FileOutputStream(
								file);

						byte[] tmpBuf = new byte[1024];
						int tmpLen = 0;
						while ((tmpLen = fileInStream.read(tmpBuf)) > 0) {
							fileOutStream.write(tmpBuf, 0, tmpLen);
						}
						fileInStream.close();
						fileOutStream.close();
						Log.e("下载文件的大小", "下载文件大小：" + file.length());
						downloadOk = true;
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} else {
			Log.e("downloadUrl", fileName + "已存在");
			downloadOk = true;
		}

		return downloadOk;
	}
	/**
	 * @param url
	 *            servlet的地址
	 * @param params
	 *            要传递的参数
	 * @param files
	 *            要上传的文件
	 * @return true if upload success else false
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static boolean downFile(String urlo, String filepath,
			Map<String, String> rawparams) throws ClientProtocolException,
			IOException {
		boolean downloadOk = false;
		String url;
		String sessionId = rawparams.get("sessionId");
		String fileName = rawparams.get("fileName");
		String functionCode = rawparams.get("functionCode");
		String path1 = filepath + fileName;
		HttpClient client = new DefaultHttpClient();// 开启一个客户端 HTTP 请求
		url = urlo + "&" + "fileName=" + fileName + "&" + "functionCode="
				+ functionCode;
		HttpPost post = new HttpPost(url);// 创建 HTTP POST 请求
		if (null != sessionId) {
			post.setHeader("Cookie", "JSESSIONID=" + sessionId);
		}

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器兼容模式
		// 请求超时 add by risa
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
		// 读取超时 add by risa
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
		HttpEntity entity = builder.build();// 生成 HTTP POST 实体
		post.setEntity(entity);// 设置请求参数
		File dbFile = new File(path1);
		if (!dbFile.exists()) {
			HttpResponse response = client.execute(post);// 发起请求 并返回请求的响应
			if (response.getStatusLine().getStatusCode() == 200) {

				HttpEntity respEnt = response.getEntity();

				Boolean isStream = respEnt.isStreaming();
				if (isStream) {
					try {
						InputStream fileInStream = respEnt.getContent();
						Log.e("下载文件流大小", "下载文件大小=" + respEnt.getContentLength());

						File file = new File(path1);
						FileOutputStream fileOutStream = new FileOutputStream(
								file);

						byte[] tmpBuf = new byte[1024];
						int tmpLen = 0;
						while ((tmpLen = fileInStream.read(tmpBuf)) > 0) {
							fileOutStream.write(tmpBuf, 0, tmpLen);
						}
						fileInStream.close();
						fileOutStream.close();
						Log.e("下载文件的大小", "下载文件大小：" + file.length());
						downloadOk = true;
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} else {
			Log.e("downloadUrl", fileName + "已存在");
			downloadOk = true;
		}

		return downloadOk;
	}

	
}
